#include <stdio.h>
#include <stdlib.h>
#include <libusb-1.0/libusb.h>

// #define VENDOR_ID 0x0e0f // 你的鼠标的供应商ID
// #define PRODUCT_ID 0x0003 // 你的鼠标的产品ID
// 有线鼠标
// #define VENDOR_ID 0x093a // 你的鼠标的供应商ID
// #define PRODUCT_ID 0x2510 // 你的鼠标的产品ID
// #define ENDPOINT_IN 0x81 // 输入端点

// 无线鼠标
#define VENDOR_ID 0x25a7 // 你的鼠标的供应商ID
#define PRODUCT_ID 0xfa23 // 你的鼠标的产品ID
#define ENDPOINT_IN 0x82 // 输入端点
#define MAX_BUF_SIZE 8 // 最大缓冲区大小

int main() {
    libusb_device_handle *devh = NULL;
    int ret;
    unsigned char buf[MAX_BUF_SIZE];

    ret = libusb_init(NULL);
    if (ret < 0) {
        fprintf(stderr, "Error initializing libusb: %s\n", libusb_error_name(ret));
        return 1;
    }

    devh = libusb_open_device_with_vid_pid(NULL, VENDOR_ID, PRODUCT_ID);
    if (!devh) {
        fprintf(stderr, "Could not find/open USB device.\n");
        return 1;
    }

    libusb_set_auto_detach_kernel_driver(devh, 1);

    ret = libusb_claim_interface(devh, 0);
    if (ret < 0) {
        fprintf(stderr, "Cannot claim interface: %s\n", libusb_error_name(ret));
        return 1;
    }

    printf("Reading data from the mouse...\n");

    while (1) {
        int actual_length;
        ret = libusb_interrupt_transfer(devh, ENDPOINT_IN, buf, sizeof(buf), &actual_length, 5000);
        if (ret == 0 && actual_length == MAX_BUF_SIZE) {
            // 在这里处理数据报告
            printf("Received data: ");
            for (int i = 0; i < actual_length; i++) {
                printf("%02x ", buf[i]);
            }
            printf("\n");
        } else if (ret == LIBUSB_ERROR_TIMEOUT) {
            fprintf(stderr, "libusb_interrupt_transfer timout\n");
        } else {
            fprintf(stderr, "Interrupt transfer error: %s\n", libusb_error_name(ret));
            break;
        }
    }

    libusb_release_interface(devh, 0);
    libusb_close(devh);
    libusb_exit(NULL);

    return 0;
}
